<?php
/**
 * Here is your custom functions.
 */


use app\backend\model\SysMenu;
use app\backend\model\SysUser;
use app\backend\model\SysUserMenu;
use support\Response;
use support\view\Raw;
use Webman\Config;

function include_array()
{
    return [
        'header' => '通用CSS',
        'footer' => '通用JS',
        'ztree' => 'ztree树插件',
        'select2' => 'select2下拉框插件',
        'bootstrap_select' => 'bootstrap-select下拉框插件',
        'datetimepicker' => 'datetimepicker日期和时间插件',
        'layout' => 'ui布局插件',
        'summernote' => 'summernote富文本编辑器插件',
        'cropbox' => 'cropbox图像裁剪插件',
        'jasny' => 'jasny功能扩展插件',
        'fileinput' => 'fileinput文件上传插件',
        'duallistbox' => 'duallistbox双列表框插件',
        'suggest' => 'suggest搜索自动补全',
        'typeahead' => 'typeahead搜索自动补全',
        'jsonview' => 'jsonview格式化和语法高亮JSON格式数据查看插件',
        'steps' => 'jquery.steps表单向导插件',
        'echarts' => 'ECharts百度统计图表插件',
        'table_drag' => '表格拖拽插件',
        'table_rowedit' => '表格行内编辑插件',
        'moment' => 'moment js',
        'formjson' => '表单序列化为Json',
        'clipboard' => 'clipboard复制',
        'tmpl' => 'jquery tmpl',
        'highlight' => '代码高亮',
    ];
}

/**
 * 加载js css 组件
 *
 * @param $name
 * @throws Exception
 */
function view_include(string $name)
{
    if (!in_array($name, array_keys(include_array()))) {
        throw new Exception("Wrong Plugin Name: $name");
    }
    static $handler;
    if (null === $handler) {
        $handler = config('view.handler');
    }
    if ($handler !== Raw::class) {
        throw new Exception('Wrong View Handler');
    }
    $view_path = \app_path() . "/view_include.php";
    $paramsName = 'include_' . $name;
    $$paramsName = true;

    include $view_path;
}

function params(string $name, $default = null)
{
    return Config::get('params.' . $name, $default);
}

function json_result(int $code, string $msg = '', $data = null, $total = null)
{
    $notes = [
        '200' => '请求成功.',
        '210' => '请求错误.',
    ];
    $msg = $msg ? $msg : (isset($notes[$code]) ? $notes[$code] : '');
    $retArray = [
        'code' => $code,
        'msg' => $msg
    ];
    if (empty($data) && !is_array($data)) {
        $retArray['data'] = (object)[];
    } else {
        $retArray['data'] = $data;
    }
    if (!is_null($total)) {
        $retArray['total'] = $total;
    }

    return json($retArray);
}

/**
 * json统一返回的成功数据
 *
 * @param string $msg 成功的消息
 * @param object|array $data 成功返回的数据
 * @return Response
 */
function json_success(string $msg, $data = null)
{
    return json_result(200, $msg, $data);
}

/**
 * json统一返回的失败数据
 *
 * @param string $msg 失败的消息
 * @param object|array $data 失败返回的数据
 * @return Response
 */
function json_error(string $msg, $data = null)
{
    return json_result(210, $msg, $data);
}

/**
 * 用户列表ajax调用的返回
 *
 * @param array $data 数据
 * @param int $total 数据总量
 * @param string $msg 返回信息
 * @return Response
 */
function json_rows($data = [], $total = 0, $msg = '')
{
    return json_result(200, $msg, $data, $total);
}

function configure($object, $properties)
{
    foreach ($properties as $name => $value) {
        $object->$name = $value;
    }

    return $object;
}

function menus($parentId = 0)
{
    /** @var SysUser $sysUser */
    $sysUser = SysUser::query()
        ->where('auid', \support\XunshanContainer::user()->getIdentity()->getId())
        ->first();
    if (!$sysUser) {
        return redirect('/backend/login/index');
    }
    if ($sysUser->admin_type == 1 || $sysUser->data_scope == 1) {
        $menus = SysMenu::query()
            ->select(['id', 'menu_name', 'action', 'menu_type', 'icon'])
            ->where([
                ['menu_type', '<>', 'F'],
                ['action', '<>', '/backend/dashboard/index'], //过滤掉仪表盘
                ['parent_id', '=', $parentId]
            ])
            ->orderBy('sort', 'DESC')
            ->get()->toArray();
    } else {
        $sysUserMenus = SysUserMenu::query()
            ->where('auid', \support\XunshanContainer::user()->getIdentity()->getId())
            ->get()->toArray();
        $userActions = array_column($sysUserMenus, 'menu_id');
        $menus = SysMenu::query()
            ->select(['id', 'menu_name', 'action', 'menu_type', 'icon'])
            ->where([
                ['menu_type', '<>', 'F'],
                ['action', '<>', '/backend/dashboard/index'], //过滤掉仪表盘
                ['parent_id', '=', $parentId],
            ])
            ->whereIn('id', $userActions)
            ->orderBy('sort', 'DESC')
            ->get()->toArray();
    }
    foreach ($menus as &$menu) {
        $menu['child_menus'] = menus($menu['id']);
    }

    return $menus;
}

